<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace App\Components;

/**
 * Description of UpYun
 *
 * @author Xuebing
 */
class UpYun {
    
    const BUCKET_NAME = 'hxtz-8518';
    const OPERATOR_NAME = 'wealth';
    const OPERATOR_PWD = 'wealth8518';
    
    const HOST = 'http://v0.api.upyun.com';
    
    public static function upload($file,$fileName,$folder){
        $fileSize = filesize($file);
        //文件上传到服务器的服务端路径
        $str_Server = config('app.server');
        $uri = '/' . static::BUCKET_NAME . '/' . $str_Server . '/' . $folder . '/' . date('Ymd') . '/' . $fileName;
        //生成签名时间。得到的日期格式如：Thu, 11 Jul 2014 05:34:12 GMT
        $date = gmdate('D, d M Y H:i:s \G\M\T');
        $sign = md5("PUT&{$uri}&{$date}&{$fileSize}&".md5(static::OPERATOR_PWD));
        
        $ch = curl_init('http://v0.api.upyun.com' . $uri);

        $headers = array(
            "Expect:",
            "Date: ".$date, // header 中需要使用生成签名的时间
            "Authorization: UpYun " . static::OPERATOR_NAME . ":".$sign
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_PUT, true);

        $fh = fopen($file, 'rb');
        curl_setopt($ch, CURLOPT_INFILE, $fh);
        curl_setopt($ch, CURLOPT_INFILESIZE, $fileSize);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec($ch);
        if(curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
            return '/' . $str_Server . '/' . $folder . '/' . date('Ymd') . '/' . $fileName;
        } else {
            throw new \Exception($file . '上传失败');
        }
        curl_close($ch);
    }
    
    
}
